package view

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import app.AppContext
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.github.ybq.android.spinkit.SpinKitView
import com.github.ybq.android.spinkit.SpriteFactory
import com.github.ybq.android.spinkit.Style
import com.hontech.pizzav2.R
import db.WaresCargo
import ext.log
import ext.setAnim
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import manager.LOCATION_UK
import manager.LOCATION_US
import manager.MY_LOCATION

class MenuItemView : LinearLayout {
    companion object {
        val WIDTH = AppContext.resources.getDimension(R.dimen.x200).toInt()
        val HEIGHT = AppContext.resources.getDimension(R.dimen.y260).toInt()

    }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    private val textViewName: TextView
    private val imageView: ImageView
    private val textViewSold: TextView
    private val progress: SpinKitView
    private val cardView: CardView
    private val textViewPrice: TextView

    init {
        orientation = VERTICAL
        val params = ViewGroup.LayoutParams(WIDTH, HEIGHT)
        setBackgroundColor(Color.TRANSPARENT)
        layoutParams = params

        cardView = CardView(context)
        cardView.setCardBackgroundColor(Color.BLACK)
        cardView.cardElevation = 5f
        cardView.radius = 10f
        val params2 = LinearLayout.LayoutParams(WIDTH, WIDTH)
        cardView.layoutParams = params2
        addView(cardView)

        textViewName = TextView(context)
        textViewName.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15f)
        textViewName.setTextColor(Color.WHITE)
        textViewName.gravity = Gravity.CENTER
        textViewName.maxLines = 2
        val params1 = LinearLayout.LayoutParams(WIDTH, LayoutParams.WRAP_CONTENT)
        textViewName.layoutParams = params1
        addView(textViewName)

        textViewPrice = TextView(context)
        textViewPrice.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15f)
        textViewPrice.setTextColor(Color.WHITE)
        textViewPrice.gravity = Gravity.CENTER
        val params5 = LinearLayout.LayoutParams(WIDTH, LayoutParams.WRAP_CONTENT)
        textViewPrice.layoutParams = params5
        addView(textViewPrice)

        imageView = ImageView(context)
        imageView.scaleType = ImageView.ScaleType.FIT_XY
        val params3 = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        params3.gravity = Gravity.CENTER
        imageView.layoutParams = params3
        cardView.addView(imageView)

        val shape = GradientDrawable()
        shape.cornerRadius = 10f
        shape.setColor(resources.getColor(R.color.color_shadow))

        textViewSold = TextView(context)
        textViewSold.gravity = Gravity.CENTER
        textViewSold.text = "Sold\r\nout"
        textViewSold.background = shape
        textViewSold.setTextColor(Color.RED)
        textViewSold.setTextSize(TypedValue.COMPLEX_UNIT_PX, 50f)
        textViewSold.layoutParams = params3
        cardView.addView(textViewSold)

        val params4 = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        params4.setMargins(10, 10, 10, 10)
        params4.gravity = Gravity.CENTER
        progress = SpinKitView(context)
        progress.setColor(resources.getColor(android.R.color.holo_orange_light))
        progress.setIndeterminateDrawable(SpriteFactory.create(Style.CIRCLE))
        progress.layoutParams = params4
        cardView.addView(progress)
    }

    fun setWaresInfo(info: WaresCargo, onItemClick: (Int) -> Unit, position: Int) {
        setImageWithUrl(info.wares.minImageUrl)
        if (info.cargos.isEmpty()) {
            imageView.setOnClickListener { }
            imageView.setOnTouchListener { _, _ -> false }
            textViewSold.visibility = View.VISIBLE
        } else {
            imageView.setAnim()
            imageView.setOnClickListener { onItemClick(position) }
            textViewSold.visibility = View.GONE
        }
        textViewName.text = info.wares.name

        if (MY_LOCATION == LOCATION_US) {
            textViewPrice.text = "$${info.wares.priceStr}"
        } else if (MY_LOCATION == LOCATION_UK) {
            textViewPrice.text = "￡${info.wares.priceStr}"
        }
    }

    private fun setImageWithUrl(url: String) {
        log("设置图片:${url}")

        imageView.setImageResource(R.drawable.shape_translate)
        progress.visibility = View.VISIBLE
        val options = RequestOptions().transform(RoundedCornersTransformation(10, 0)).error(
            R.drawable.ic_image_load_error
        ).diskCacheStrategy(
            DiskCacheStrategy.ALL
        ).skipMemoryCache(true)
        imageView.setTag(R.id.imageId, url)
        Glide.with(AppContext).load(url).apply(options)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?, model: Any?, target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    val info = imageView.getTag(R.id.imageId)
                    if (info != null && info == url) {
                        progress.visibility = View.GONE
                    }
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?, model: Any?,
                    target: Target<Drawable>?, dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    val info = imageView.getTag(R.id.imageId)
                    if (info != null && info == url) {
                        progress.visibility = View.GONE
                    }
                    return false
                }
            }).into(imageView)
    }
}